import React from 'react';
import { Card, Row, Col, Statistic, Descriptions, Tag, Space } from 'antd';
import { ArrowUpOutlined, ArrowDownOutlined, MinusOutlined } from '@ant-design/icons';

interface DynamicStatistics {
  id: string;
  cityId: string;
  statisticType: string;
  statisticDate: string;
  dataPointCount: number;
  createdAt: string;
  [key: string]: any; // 动态统计数据 (如 temperature_avg, humidity_max 等)
}

interface DynamicStatisticsDisplayProps {
  data: DynamicStatistics;
  showTrends?: boolean;
  compact?: boolean;
}

export const DynamicStatisticsDisplay: React.FC<DynamicStatisticsDisplayProps> = ({ 
  data, 
  showTrends = false, 
  compact = false 
}) => {
  // 按指标分组统计数据
  const groupedMetrics = React.useMemo(() => {
    const groups: Record<string, Record<string, any>> = {};
    
    Object.entries(data).forEach(([key, value]) => {
      if (['id', 'cityId', 'statisticType', 'statisticDate', 'dataPointCount', 'createdAt'].includes(key)) {
        return;
      }
      
      const parts = key.split('_');
      if (parts.length >= 2) {
        const metricKey = parts.slice(0, -1).join('_');
        const aggType = parts[parts.length - 1];
        
        if (!groups[metricKey]) {
          groups[metricKey] = {};
        }
        groups[metricKey][aggType] = value;
      }
    });
    
    return groups;
  }, [data]);

  // 获取指标显示配置
  const getMetricConfig = (metricKey: string) => {
    const configs: Record<string, { name: string; unit: string; color: string }> = {
      temperature: { name: '温度', unit: '°C', color: '#1890ff' },
      humidity: { name: '湿度', unit: '%', color: '#52c41a' },
      pressure: { name: '气压', unit: 'hPa', color: '#faad14' },
      windSpeed: { name: '风速', unit: 'm/s', color: '#722ed1' },
      windDirection: { name: '风向', unit: '°', color: '#eb2f96' },
      visibility: { name: '能见度', unit: 'km', color: '#13c2c2' },
      uvIndex: { name: '紫外线指数', unit: '', color: '#f5222d' },
      weatherCondition: { name: '天气状况', unit: '', color: '#096dd9' }
    };
    
    return configs[metricKey] || { name: metricKey, unit: '', color: '#666' };
  };

  // 获取趋势图标
  const getTrendIcon = (current: number, previous?: number) => {
    if (previous === undefined) return <MinusOutlined />;
    
    const change = current - previous;
    if (Math.abs(change) < 0.1) return <MinusOutlined style={{ color: '#666' }} />;
    
    return change > 0 
      ? <ArrowUpOutlined style={{ color: '#52c41a' }} />
      : <ArrowDownOutlined style={{ color: '#f5222d' }} />;
  };

  if (compact) {
    return (
      <Card size="small" style={{ marginBottom: 8 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <div>
            <Tag color="blue">{data.statisticType}</Tag>
            <span style={{ marginLeft: 8, fontSize: 14, fontWeight: 500 }}>
              {new Date(data.statisticDate).toLocaleDateString('zh-CN')}
            </span>
          </div>
          <div>
            <Tag>{data.dataPointCount} 条数据</Tag>
          </div>
        </div>
        
        <Row gutter={8} style={{ marginTop: 8 }}>
          {Object.entries(groupedMetrics).slice(0, 4).map(([metricKey, values]) => {
            const config = getMetricConfig(metricKey);
            const avgValue = values.avg;
            
            return avgValue !== undefined && (
              <Col span={6} key={metricKey}>
                <Statistic
                  title={config.name}
                  value={avgValue}
                  suffix={config.unit}
                  precision={1}
                  valueStyle={{ fontSize: 14, color: config.color }}
                />
              </Col>
            );
          })}
        </Row>
      </Card>
    );
  }

  return (
    <Card 
      title={`${data.statisticType} 统计数据`}
      extra={
        <Space>
          <Tag color="blue">{new Date(data.statisticDate).toLocaleDateString('zh-CN')}</Tag>
          <Tag>{data.dataPointCount} 条数据</Tag>
        </Space>
      }
    >
      <Row gutter={16}>
        {Object.entries(groupedMetrics).map(([metricKey, values]) => {
          const config = getMetricConfig(metricKey);
          
          return (
            <Col span={8} key={metricKey} style={{ marginBottom: 16 }}>
              <Card size="small" title={config.name} headStyle={{ backgroundColor: '#fafafa' }}>
                <Row gutter={8}>
                  {values.avg !== undefined && (
                    <Col span={8}>
                      <Statistic
                        title="平均"
                        value={values.avg}
                        suffix={config.unit}
                        precision={1}
                        valueStyle={{ fontSize: 14, color: config.color }}
                      />
                    </Col>
                  )}
                  {values.max !== undefined && (
                    <Col span={8}>
                      <Statistic
                        title="最高"
                        value={values.max}
                        suffix={config.unit}
                        precision={1}
                        valueStyle={{ fontSize: 14, color: '#f5222d' }}
                      />
                    </Col>
                  )}
                  {values.min !== undefined && (
                    <Col span={8}>
                      <Statistic
                        title="最低"
                        value={values.min}
                        suffix={config.unit}
                        precision={1}
                        valueStyle={{ fontSize: 14, color: '#1890ff' }}
                      />
                    </Col>
                  )}
                  {values.dominant !== undefined && (
                    <Col span={24}>
                      <div style={{ textAlign: 'center', marginTop: 8 }}>
                        <Tag color={config.color} style={{ fontSize: 12 }}>
                          主要: {values.dominant}
                        </Tag>
                      </div>
                    </Col>
                  )}
                </Row>
              </Card>
            </Col>
          );
        })}
      </Row>
      
      <Descriptions
        title="统计信息"
        bordered
        column={2}
        size="small"
        style={{ marginTop: 16 }}
      >
        <Descriptions.Item label="统计日期">
          {new Date(data.statisticDate).toLocaleDateString('zh-CN')}
        </Descriptions.Item>
        <Descriptions.Item label="数据点数量">
          {data.dataPointCount}
        </Descriptions.Item>
        <Descriptions.Item label="统计类型">
          <Tag color="blue">{data.statisticType}</Tag>
        </Descriptions.Item>
        <Descriptions.Item label="生成时间">
          {new Date(data.createdAt).toLocaleString('zh-CN')}
        </Descriptions.Item>
      </Descriptions>
    </Card>
  );
};

export default DynamicStatisticsDisplay;